<template>
  <n-modal v-model:show="modalVisible" preset="card" title="创建链接" class="w-350px">
    <n-form ref="formRef" label-placement="left" :label-width="60" :model="formModel" :rules="rules">
      <n-form-item label="平台" path="platform">
        <n-cascader v-model:value="formModel.platform" placeholder="请选择平台" check-strategy="child" :options="platformOptions" />
      </n-form-item>
      <n-form-item label="短剧" path="playlet">
        <n-cascader v-model:value="formModel.playlet" placeholder="请选择短剧" :options="playletOptions" check-strategy="child"  remote :on-Load="handleLoad" />
      </n-form-item>
      <n-space class="w-full pt-16px" :size="24" justify="end">
        <n-button class="w-72px" @click="closeModal">取消</n-button>
        <n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
      </n-space>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue';
import type { FormInst, FormItemRule, CascaderOption } from 'naive-ui';
import { selectAllDuanjuList,selectAllDuanjuEpisodesList,createOperatorLinks } from '@/service';
import { formRules, createRequiredFormRule, localStg } from '@/utils';

export interface Props {
  /** 弹窗可见性 */
  visible: boolean;
}

defineOptions({ name: 'TableActionModal' });

const props = defineProps<Props>();

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'refresh'): void;
}

const emit = defineEmits<Emits>();

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});
// 关闭弹框
const closeModal = () => {
  modalVisible.value = false;
};

// 表单ref对象
const formRef = ref<HTMLElement & FormInst>();

type FormModel = any;

// 表单数据
const formModel = reactive<FormModel>(createDefaultFormModel());

// 初始化表单数据
function createDefaultFormModel(): FormModel {
  return {
    platform: null, // 平台：h5，wx，dy
    playlet: null
  };
}

// 表单验证
const rules: Record<keyof FormModel, FormItemRule | FormItemRule[]> = {
  platform: createRequiredFormRule('请选择平台'),
  playlet: createRequiredFormRule('请选择短剧'),
};



// 更新表单数据
function handleUpdateFormModel() {
  Object.assign(formModel, createDefaultFormModel());
}

// 添加
async function handleSubmit() {
  const err = await formRef.value?.validate();
  if (!err) {
    let playlet = JSON.parse(formModel.playlet)
    let params = {
      duanju_id: playlet.duanju_id,
      episodes: playlet.episodes,
      duanju_name: playlet.duanju_name,
      platform: formModel.platform,
    }
    let res:any = await createOperatorLinks(params)
    if(res.code == 0) {
      window.$message?.success('添加成功!');
      closeModal();
      emit('refresh');
    }
    
  }
}

// 平台选择options
const platformOptions = ref([
  {
    label: 'H5',
    value: 'h5'
  },
  {
    label: '抖音小程序',
    value: 'dy'
  },
  {
    label: '微信小程序',
    value: 'wx'
  },
])
// 短剧options
let playletOptions = ref([])
// 获取短剧选择options
async function handleSelectAllDuanjuList() {
  let { data } = await selectAllDuanjuList()
  if (data) {
    playletOptions.value = data.map((e:any) => {
      return {
        label: e.Name,
        value: e.Id,
        depth: 1,
        isLeaf: false
      }
    })  
  }
}
// 获取剧集选择
function handleLoad(option: CascaderOption) {
  return new Promise<void>( async (resolve,reject) => {
    let params = {
      duanju_id: option.value
    }
    let { data } = await selectAllDuanjuEpisodesList(params)
    if(data) {
      option.children = data.episodesList.map((e:any) => {
        return {
          label: `第${e}集`,
          value: JSON.stringify({
            duanju_id: option.value,
            duanju_name: option.label,
            episodes: e
          }),
          depth: 2,
          isLeaf: true
        }
      })
      resolve()
    }else {
      reject()
    }
  })

}

watch(
  () => props.visible,
  newValue => {
    if (newValue) {
      handleUpdateFormModel();
    }
  }
);

function init() {
  handleSelectAllDuanjuList()
}

init()
</script>

<style scoped></style>
